import psutil
import requests
import json
import time
import socket


# 获取本机磁盘使用率和剩余空间G信息
def get_disk_info():
    """
    获取磁盘信息
    :return:  磁盘总容量，磁盘已使用（单位G）
    """
    total_size_all = 0
    free_disk_size_all = 0
    # 循环磁盘分区
    for disk in psutil.disk_partitions():
        # 读写方式 光盘 or 有效磁盘类型
        if 'cdrom' in disk.opts or disk.fstype == '':
            continue
        disk_name_arr = disk.device.split(':')
        disk_name = disk_name_arr[0]
        mountpoint = disk.mountpoint
        disk_info = psutil.disk_usage(mountpoint)
        # 磁盘总的空间，单位G
        # total_size = disk_info.total / (1024 * 1024 * 1024)
        total_size = disk_info.total
        # 磁盘剩余空间，单位G
        # free_disk_size = disk_info.free / (1024 * 1024 * 1024)
        free_disk_size = disk_info.free
        total_size_all += total_size
        free_disk_size_all += free_disk_size
    use_disk_size = total_size_all - free_disk_size_all
    use_info = "%.2f%%" % (use_disk_size / total_size_all)
    return total_size_all, use_disk_size, use_info


# cpu信息
def get_cpu_info():
    """
    获取CPU使用率
    :return:  使用率，（%无小数）
    """
    cpu_percent = psutil.cpu_percent(interval=1)
    cpu_info = "%.2f%%" % cpu_percent
    return cpu_info


# 内存信息
def get_memory_info():
    """
    获取设备内存信息
    :return:  内存总容量，内存使用量, 内存空余量（单位G），内存使用率（%无小数）
    """
    virtual_memory = psutil.virtual_memory()
    used_memory = virtual_memory.used / (1024 * 1024 * 1024)
    # free_memory = virtual_memory.free / 1024 / 1024 / 1024
    total_memory = virtual_memory.total / (1024 * 1024 * 1024)
    free_memory = total_memory - used_memory
    memory_percent = "%.2f%%" % virtual_memory.percent
    return total_memory, used_memory, free_memory, memory_percent


def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip


def restful_api(url, method, args=None, TK=None, value_json=None):
    ''' *函数说明*: 执行Restful API请求

        *参数说明*:
           url:         HTTP请求的地址, 例如: http://api/equip_group/add
           method:      HTTP请求方式, 例如:  GET, POST, PUT, DELETE...
           args:        HTTP请求参数, 以字典形式提供
           TK:          Cookie: TK=F4823B61-2F37-40F9-9212-3BA17F5DEE81-3169E157-5C80-407A-8E45-20A3741DC1FE
           value_json   args仅仅value需要json格式
        *example*:
            restful_api  ${add_group}  ${post}  @{data}  TK=${TK}

    '''
    ret = ''
    headers = {"Content-Type": "application/json; charset=UTF-8"}

    s = requests.session()
    for i in range(5):
        try:
            if method == 'post':
                if value_json:
                    for key in args:
                        v = args[key]
                        args[key] = json.dumps(v)
                    ret = s.post(url, data=args, headers=headers, timeout=120)
                else:
                    ret = s.post(url, data=args, headers=headers, timeout=120)
            elif method == 'get':
                ret = s.get(url, data=args, headers=headers, timeout=120)
            print(ret.content)
            return ret.content
        except Exception as e:
            print(e)


if __name__ == '__main__':
    while 1:
        time.sleep(10)
        ticks = time.time()  # 时间戳
        total_size_all, use_disk_size, use_info = get_disk_info()  # 磁盘信息
        cpu_info = get_cpu_info()  # cpu使用率
        total_memory, used_memory, free_memory, memory_percent = get_memory_info()  # 内存信息
        host_ip = get_host_ip()
        url = 'http://127.0.0.1:8000'
        args = {'host_ip': host_ip, 'total_size_all': total_size_all, 'use_disk_size': use_disk_size,
                'use_info': use_info, 'cpu_info': cpu_info, 'total_memory': total_memory, 'used_memory': used_memory,
                'free_memory': free_memory, 'memory_percent': memory_percent, 'time': ticks}
        args = json.dumps(args)
        restful_api(url, 'post', args)